package com.zhangdi.zddemo.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReenterLock {
    ReentrantLock lock  = new ReentrantLock();
   int volume = 0;
    public void A(){
        try {
            if(lock.tryLock(25, TimeUnit.SECONDS)) {
                System.out.println("A获取，volume=" + volume);
                try {
                    Thread.sleep(20000L);
                } finally {
                    System.out.println("A最终，volume=" + volume);
                    lock.unlock();
                }
            }else {
                System.out.println("A获取失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void B(){
        try {
            if(lock.tryLock(25, TimeUnit.SECONDS)){
                System.out.println("B获取，volume=" + volume);
                try {
                    if(volume < 10) {
                        while (volume < 10) {
                            volume++;
                        }
                    } else {
                        volume++;
                    }
                }finally {
                    System.out.println("B最终，volume=" + volume);
                    lock.unlock();
                }
            } else {
                System.out.println("B获取失败");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ReenterLock test = new ReenterLock();

        Thread thread = new Thread(() -> {
            test.A();
        });
//        Thread thread1 = new Thread(() -> test.B());

        thread.start();
        test.lock.lock();
        try {
            System.out.println("ooooo");
            Thread.sleep(200000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            test.lock.unlock();
        }

//        thread1.start();
    }
}
